/// Support for doing something awesome.
///
/// More dartdocs go here.
library;

export 'src/current_base.dart';

// TODO: Export any libraries intended for clients of this package.
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';

// 模拟事件队列类
class EventQueue {
  // 模拟事件队列，使用 Queue 存储函数
  final Queue<Function> _events = Queue<Function>();

  // 检查队列中是否有事件等待处理
  bool waitForEvent() {
    return _events.isNotEmpty;
  }

  // 处理队列中的下一个事件
  void processNextEvent() {
    if (_events.isNotEmpty) {
      final event = _events.removeFirst();
      event();
    }
  }

  // 向队列中添加一个事件
  void addEvent(Function event) {
    _events.add(event);
  }
}

// 模拟 http.get 方法，返回一个 Future
Future<MockResponse> mockHttpGet(String url) {
  return Future.delayed(Duration(seconds: 2), () {
    // 模拟成功响应
    return MockResponse(200, 'Mock response from $url');
  });
}

// 模拟响应类
class MockResponse {
  final int statusCode;
  final String body;

  MockResponse(this.statusCode, this.body);
}

// 异步读取文件函数
Future<String> _readFileAsync(String filename) async {
  final file = File(filename);
  final contents = await file.readAsString();
  return contents.trim();
}

// 同步读取文件函数
String _readFileSync(String filename) {
  final file = File(filename);
  final contents = file.readAsStringSync();
  return contents.trim();
}

// 处理流数据，对每个值进行累加并返回新的流
Stream<int> sumStream(Stream<int> stream) async* {
  var sum = 0;
  await for (final value in stream) {
    yield sum += value;
  }
}

// 一个耗时的斐波那契数列计算函数
int slowFib(int n) => n <= 1 ? 1 : slowFib(n - 1) + slowFib(n - 2);

// 使用 Isolate 计算斐波那契数列
void fib40() async {
  var result = await Isolate.run(() => slowFib(40));
  print('Fib(40) = $result');
}

// 模拟查找版本号的异步函数
Future<String> lookUpVersion() async {
  await Future.delayed(Duration(seconds: 1));
  return '1.0.0';
}

// 检查版本号的异步函数
Future<void> checkVersion() async {
  var version = await lookUpVersion();
  print('Version: $version');
}

// 模拟查找入口点的异步函数
Future<String> findEntryPoint() async {
  await Future.delayed(Duration(seconds: 1));
  return 'entry_point.dart';
}

// 模拟运行可执行文件的异步函数
Future<int> runExecutable(String entrypoint, List<String> args) async {
  await Future.delayed(Duration(seconds: 1));
  return 0;
}

// 模拟刷新并退出的异步函数
Future<void> flushThenExit(int exitCode) async {
  await Future.delayed(Duration(seconds: 1));
  print('Exiting with code $exitCode');
}

// 自定义错误类
class RemoteError {
  final String message;
  final String stackTrace;

  RemoteError(this.message, this.stackTrace);

  @override
  String toString() {
    return 'RemoteError: $message';
  }
}

// 用于在 Isolate 中处理 JSON 解析的 Worker 类
class Worker {
  final SendPort _commands;
  final ReceivePort _responses;
  final Map<int, Completer<Object?>> _activeRequests = {};
  int _idCounter = 0;
  bool _closed = false;

  // 私有构造函数，初始化响应端口的监听
  Worker._(this._responses, this._commands) {
    _responses.listen(_handleResponsesFromIsolate);
  }

  // 创建一个新的 Worker 实例
  static Future<Worker> spawn() async {
    // 创建一个接收端口并添加初始消息处理程序
    final initPort = RawReceivePort();
    final connection = Completer<(ReceivePort, SendPort)>.sync();
    initPort.handler = (initialMessage) {
      final commandPort = initialMessage as SendPort;
      connection.complete((
        ReceivePort.fromRawReceivePort(initPort),
        commandPort,
      ));
    };
    // 启动 Isolate
    try {
      await Isolate.spawn(_startRemoteIsolate, initPort.sendPort);
    } on Object {
      initPort.close();
      rethrow;
    }
    // 等待连接完成
    final (ReceivePort receivePort, SendPort sendPort) =
        await connection.future;

    return Worker._(receivePort, sendPort);
  }

  // 解析 JSON 字符串的异步方法
  Future<Object?> parseJson(String message) async {
    if (_closed) throw StateError('Closed');
    final completer = Completer<Object?>.sync();
    final id = _idCounter++;
    _activeRequests[id] = completer;
    _commands.send((id, message));
    return await completer.future;
  }

  // 处理从 Isolate 发送回来的响应
  void _handleResponsesFromIsolate(dynamic message) {
    final (int id, Object? response) = message as (int, Object?);
    final completer = _activeRequests.remove(id)!;

    if (response is RemoteError) {
      completer.completeError(response);
    } else {
      completer.complete(response);
    }
  }

  // 关闭 Worker 实例
  void close() {
    if (!_closed) {
      _closed = true;
      _commands.send('shutdown');
      if (_activeRequests.isEmpty) _responses.close();
      print('--- port closed --- ');
    }
  }

  // 在 Isolate 中启动远程处理逻辑
  static void _startRemoteIsolate(SendPort sendPort) {
    final receivePort = ReceivePort();
    sendPort.send(receivePort.sendPort);
    _handleCommandsToIsolate(receivePort, sendPort);
  }

  // 处理发送到 Isolate 的命令
  static void _handleCommandsToIsolate(
    ReceivePort receivePort,
    SendPort sendPort,
  ) {
    receivePort.listen((message) {
      if (message == 'shutdown') {
        receivePort.close();
        return;
      }
      final (int id, String jsonText) = message as (int, String);
      try {
        final jsonData = jsonDecode(jsonText);
        sendPort.send((id, jsonData));
      } catch (e) {
        sendPort.send((id, RemoteError(e.toString(), '')));
      }
    });
  }
}

void main() async {
  // 模拟事件循环
  final eventQueue = EventQueue();
  eventQueue.addEvent(() {
    print('Event 1: Simulating event processing');
  });
  eventQueue.addEvent(() {
    print('Event 2: Another event processing');
  });

  while (eventQueue.waitForEvent()) {
    eventQueue.processNextEvent();
  }

  // 模拟网络请求
  mockHttpGet('https://example.com').then((response) {
    if (response.statusCode == 200) {
      print('Success!');
    }
  });

  // 同步文件读取
  const String syncFilename = 'E:/Desktop/大二下/workspace/my_base/my_dart_base/bin/current_data.json';
  try {
    final syncFileData = _readFileSync(syncFilename);
    final syncJsonData = jsonDecode(syncFileData);
    print('Number of JSON keys (sync): ${syncJsonData.length}');
  } catch (e) {
    print('Error reading file synchronously: $e');
  }

  // 异步文件读取
  const String asyncFilename = 'E:/Desktop/大二下/workspace/my_base/my_dart_base/bin/current_data.json';
  try {
    final asyncFileData = await _readFileAsync(asyncFilename);
    final asyncJsonData = jsonDecode(asyncFileData);
    print('Number of JSON keys (async): ${asyncJsonData.length}');
  } catch (e) {
    print('Error reading file asynchronously: $e');
  }

  // 流处理
  Stream<int> stream = Stream.periodic(const Duration(seconds: 1), (i) => i * i);
  Stream<int> resultStream = sumStream(stream);
  resultStream.take(5).listen((result) {
    print('Accumulated result from stream: $result');
  });

  // 使用 Isolate 计算斐波那契数列
  fib40();

  // 检查版本号
  await checkVersion();

  // 模拟一系列异步操作
  var entrypoint = await findEntryPoint();
  var exitCode = await runExecutable(entrypoint, []);
  await flushThenExit(exitCode);

  // 使用 Worker 类解析 JSON
  final worker = await Worker.spawn();
  final jsonString = '{"key": "value"}';
  try {
    final result = await worker.parseJson(jsonString);
    print('Parsed JSON: $result');
  } catch (e) {
    print('Error parsing JSON: $e');
  }
  worker.close();
}    